package cn.djp.test3;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et1;
    private Button b1;
    private TextView tv1;
    private Button clear;
    private List<String> list;
    private StringBuffer stringBuffer;

    //字符匹配表达式
    private static final String checkEdit = "\\bOP\\S*?[0-9]\\b";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b1 = (Button) findViewById(R.id.b1);
        et1 = (EditText) findViewById(R.id.et1);
        clear = (Button) findViewById(R.id.clear);
        stringBuffer = new StringBuffer();
        tv1 = (TextView) findViewById(R.id.tv1);
        list = new ArrayList<String>();
        b1.setOnClickListener(this);
        clear.setOnClickListener(this);
        tv1.setMovementMethod(ScrollingMovementMethod.getInstance());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.b1:
                String edit = et1.getText().toString();
                if (edit.equals("")){
                    addToTextV("-->你还没有输入字符!" + '\n');
                }else {
                    if (checkData(edit)) {
                        addToTextV("-->" + edit + '\n');
                    } else {
                        addToTextV("-->请输入符合规则的字符!("+edit+")" + '\n');
                    }
                }
            break;
            case R.id.clear:
                stringBuffer = new StringBuffer();
                addToTextV("-->等待输入"+'\n');
        }
    }

    //检查用户输入的字符串是否符合规则
    public Boolean checkData(String str){
        if (Pattern.matches(checkEdit, str) && str.length() == 4) {
            return true;
        } else {
            return false;
        }
    }

    //将传入的字符显示在文本显示框
    public void addToTextV(String str) {
        stringBuffer.append(str);
        tv1.setText(stringBuffer.toString());
        et1.setText("");
    }
}
